from PIL import Image
import time
from util.ShowapiRequest import ShowapiRequest

class GetCode:
    def __init__(self,driver):
        self.driver = driver
    def get_code_image(self,filename):
        '''
        获取验证码图片
        :return:
        '''
        self.driver.save_screenshot(filename)
        code_element = self.driver.find_element_by_id('getcode_num')
        left = code_element.location['x']
        top = code_element.location['y']
        right = code_element.size['width'] + left
        height = code_element.size['height'] + top
        # 获取窗口可视范围的width和height
        html = self.driver.find_element_by_tag_name("html")

        # 设置图片重新打开的width和height
        resize_width = html.size['width']
        resize_height = html.size['height']

        # resize图片
        im = Image.open(filename)
        resize_img = im.resize((resize_width, resize_height), Image.BILINEAR)
        # 截取图片
        img = resize_img.crop((left, top, right, height))
        img.save(filename)
        time.sleep(1)

    def code_online(self,filename):
        '''
        解析验证码图片图片
        :return:
        '''
        self.get_code_image(filename)
        r = ShowapiRequest("http://route.showapi.com/184-4", "62626", "d61950be50dc4dbd9969f741b8e730f5")
        r.addBodyPara("typeId", "35")
        r.addBodyPara("convert_to_jpg", "0")
        r.addBodyPara("needMorePrecise", "0")
        r.addFilePara("image", filename)
        res = r.post()

        text = res.json()['showapi_res_body']['Result']
        time.sleep(1)
        return text